package com.innovation.ic.b1b.monitor.web.config;

import com.innovation.ic.b1b.monitor.base.value.ShardingConfig;
//import io.shardingsphere.api.algorithm.sharding.PreciseShardingValue;
//import io.shardingsphere.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

public class IdCommonShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    private ShardingConfig shardingConfig;

    public IdCommonShardingAlgorithm() {
    }

    public IdCommonShardingAlgorithm(ShardingConfig shardingConfig) {
        this.shardingConfig = shardingConfig;
    }

    /**
     * 在插入记录时，决定将记录插入到这个数据库的哪个表，这个表名的格式：表名_数字
     * @param availableTargetNames
     * @param shardingValue
     * @return
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        String target = availableTargetNames.stream().findFirst().get();
        for (String tableName : availableTargetNames) {
            if (tableName.endsWith(idToTableSuffix(shardingValue.getValue()))) {
                target = tableName;
            }
        }
        return target;
    }

    private String idToTableSuffix(Long id) {
        String idStr = String.valueOf(id);
        int total = 0;
        for (int i = 0; i < idStr.length() - 1; i++) {
            Integer num = Integer.parseInt(idStr.substring(i, i + 1));
            total += num;
        }
        return String.valueOf(total % shardingConfig.getTableNumber().intValue());
    }
}
